#include "bsp_led.h"
#include "led_strip.h"

#define LED_COLOR_GREEN 0, 7, 0
#define LED_COLOR_PURPLE 7, 0, 7
#define LED_COLOR_BLUE 0, 0, 7
#define LED_COLOR_ORANGE 7, 3, 0
#define LED_COLOR_CYAN 0, 7, 7
#define LED_COLOR_RED 7, 0, 0

static led_strip_handle_t s_led_strip = NULL;

void bsp_led_init(void)
{
    /// LED strip common configuration
    led_strip_config_t strip_config = {
        .strip_gpio_num = BSP_LED_PIN,                               // The GPIO that connected to the LED strip's data line
        .max_leds = 2,                                               // The number of LEDs in the strip,
        .led_model = LED_MODEL_WS2812,                               // LED strip model, it determines the bit timing
        .color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB, // The color component format is G-R-B
        .flags = {
            .invert_out = false, // don't invert the output signal
        },
    };

    /// RMT backend specific configuration
    led_strip_rmt_config_t rmt_config = {
        .clk_src = RMT_CLK_SRC_DEFAULT,    // different clock source can lead to different power consumption
        .resolution_hz = 10 * 1000 * 1000, // RMT counter clock frequency: 10MHz
        .mem_block_symbols = 64,           // the memory size of each RMT channel, in words (4 bytes)
        .flags = {
            .with_dma = true, // DMA feature is available on chips like ESP32-S3/P4
        },
    };

    /// Create the LED strip object
    ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &s_led_strip));
}

void bsp_led_set_state(bsp_led_state_t state)
{
    switch (state)
    {
    case LED_STATE_STARTING:
        led_strip_set_pixel(s_led_strip, 0, LED_COLOR_PURPLE);
        led_strip_set_pixel(s_led_strip, 1, LED_COLOR_PURPLE);
        led_strip_refresh(s_led_strip);
        break;
    case LED_STATE_IDLE:
        // 绿色
        led_strip_set_pixel(s_led_strip, 0, LED_COLOR_GREEN);
        led_strip_set_pixel(s_led_strip, 1, LED_COLOR_GREEN);
        led_strip_refresh(s_led_strip);
        break;
    case LED_STATE_ACTIVATING:
        led_strip_set_pixel(s_led_strip, 0, LED_COLOR_BLUE);
        led_strip_set_pixel(s_led_strip, 1, LED_COLOR_BLUE);
        led_strip_refresh(s_led_strip);
        break;
    case LED_STATE_CONNECTING:
        led_strip_set_pixel(s_led_strip, 0, LED_COLOR_ORANGE);
        led_strip_set_pixel(s_led_strip, 1, LED_COLOR_ORANGE);
        led_strip_refresh(s_led_strip);
        break;
    case LED_STATE_LISTENING:
        led_strip_set_pixel(s_led_strip, 0, LED_COLOR_CYAN);
        led_strip_set_pixel(s_led_strip, 1, LED_COLOR_CYAN);
        led_strip_refresh(s_led_strip);
        break;
    case LED_STATE_SPEAKING:
        led_strip_set_pixel(s_led_strip, 0, LED_COLOR_RED);
        led_strip_set_pixel(s_led_strip, 1, LED_COLOR_RED);
        led_strip_refresh(s_led_strip);
        break;
    default:
        break;
    }
}
